package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanValidators;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.domain.Category;
import com.spzx.product.helper.CategoryHelper;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.system.api.domain.SysUser;
import jakarta.validation.Validator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author dongdongxiaoyuanmao
 * @since 2025-03-06
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private Validator validator;

    @Override
    public List<Category> treeSelect(Long id) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId, id);
        List<Category> categoryList = baseMapper.selectList(queryWrapper);

        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryList.forEach(category -> {
                //查询数据库，看看哪个记录的parentId和本记录的id是一样的
                //如果数值大于0，就代表该记录有子节点，如果等于0，就代表没有子节点
                LambdaQueryWrapper<Category> queryWrapper1 = new LambdaQueryWrapper<>();
                //查询数据库，看看哪个记录的parentId和本记录的id是一样的
                queryWrapper1.eq(Category::getParentId, category.getId());
                Long count = baseMapper.selectCount(queryWrapper1);
                //如果大于0，设置为true，否则设置为false
                category.setHasChildren(count > 0);
            });
        }

        return categoryList;

    }

    /**
     * 导入商品类别数据
     *
     * @param categoryList    商品类别数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importCategory(List<Category> categoryList, boolean isUpdateSupport, String operName) {
//        if(CollectionUtils.isEmpty(categoryList)){
//            throw new ServiceException("导入商品类别数据不能为空！");
//        }

        if (StringUtils.isNull(categoryList) || categoryList.size() == 0) {
            throw new ServiceException("导入商品类别数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Category category : categoryList) {
            try {
                // 验证是否存在这个类别，通过id验证
                Category c = baseMapper.selectById(category.getId());
                if (StringUtils.isNull(c)) {
//                    BeanValidators.validateWithException(validator, category);
                    category.setCreateBy(operName);
                    baseMapper.insert(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、类别 " + category.getName() + " 导入成功");
                } else if (isUpdateSupport) {
//                    BeanValidators.validateWithException(validator, category);
                    category.setUpdateBy(operName);
                    baseMapper.updateById(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、类别 " + category.getName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、类别 " + category.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、类别 " + category.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    @Override
    public List<Long> getAllCategoryIdList(Long categoryId) {
        //创建一个id集合
        List<Long> idList = new ArrayList<>();
        //递归查询节点集合
        idList = getParentCategoryIdList(categoryId, idList);
        //由于我们的集合是倒序的，也就是我们先显示的三级id，其次是二级id，最后是一级id
        //所以在前端展示的时候，我们需要倒序过来，也就是先展示一级，然后是二级，最后是三级
        Collections.reverse(idList);
        return idList;
    }

    @Override
    public List<CategoryVo> getOneCategory() {
        //只获取一级分类数据
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件，只获取一级分类数据
        queryWrapper.eq(Category::getParentId, 0);
        List<Category> allCategoryListLevelOne = baseMapper.selectList(queryWrapper);
        List<CategoryVo> categoryVoList = allCategoryListLevelOne.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
        return categoryVoList;
    }

    @Override
    public List<CategoryVo> tree() {
        //一次性查询所有的类别记录
        List<Category> allCategoryList = baseMapper.selectList(null);

        //将记录转换成vo列表
        List<CategoryVo> allCategoryVoList = allCategoryList.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());

        //将记录组装成tree
        return CategoryHelper.buildTree(allCategoryVoList);
    }

    private List<Long> getParentCategoryIdList(Long categoryId, List<Long> idList) {
        //递归查询父记录节点
        //当id大于0，说明还有父节点，当id=0，说明没有父节点了，可以结束递归查询了
        while (categoryId > 0) {
            LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper
                    //需要查询该条记录的父记录是什么
                    //由于下面需要放入id，所以需要把id也查询出来
                    .select(Category::getParentId, Category::getId).eq(Category::getId, categoryId);
            //这是该条记录的父记录
            Category category = baseMapper.selectOne(queryWrapper);
            //我们需要放入的是该记录的id，而不是父亲的id
            idList.add(category.getId());
            //只要满足条件，就递归查询每个节点的父节点
            return getParentCategoryIdList(category.getParentId(), idList);
        }
        //将查询出来的id列表返回
        return idList;
    }


}
